import Heart from "@/components/Heart";
import ResizeImage from "@/components/ResizeImage";
import articleList from "@/mock/articleList";
import TopBar from "@/modules/index/components/topBar";
import TypeBar from "@/modules/index/components/typeBar";
import IndexStore from "@/modules/index/IndexStore";
import { useRouter } from "expo-router";
import { observer, useLocalObservable } from "mobx-react-lite";
import { useCallback, useEffect, useState } from "react";
import {
  Dimensions,
  Image,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
} from "react-native";
import WaterfallFlow from "../../components/WaterfallFlow";
const { width: SCREEN_WIDTH } = Dimensions.get("window");
export default observer(function IndexScreen() {
  const router = useRouter();
  const store = useLocalObservable(() => new IndexStore());
  const [isLoading_type, setIsLoading_type] = useState(true);
  useEffect(() => {
    const Loading_type = async () => {
      try {
        await store.getCategoryList();
      } catch (error) {
        console.error("Failed to fetch category list:", error);
      } finally {
        setIsLoading_type(false);
      }
    };
    Loading_type();
    store.requestHomeList();
  }, []);
  const onArticlePress = useCallback(
    (article: ArticleSimple) => () => {
      router.push(`/articleDetail?id=${article.id}`);
    },
    []
  );
  const renderItem = (item: ArticleSimple) => {
    return (
      <TouchableOpacity style={styles.item} onPress={onArticlePress(item)}>
        <ResizeImage uri={item.image} />
        <Text style={styles.titleTxt}>{item.title}</Text>
        <View style={[styles.nameLayout]}>
          <Image style={styles.avatarImg} source={{ uri: item.avatarUrl }} />
          <Text style={styles.nameTxt}>{item.userName}</Text>
          <Heart
            value={item.isFavorite}
            onValueChanged={(value: boolean) => {
              console.log(value);
            }}
          />
          <Text style={styles.countTxt}>{item.favoriteCount}</Text>
        </View>
      </TouchableOpacity>
    );
  };
  const loadMoreData = () => {
    store.requestHomeList();
  };
  const refreshNewData = () => {
    store.resetPage();
    store.requestHomeList();
  };
  const Footer = () => {
    return <Text style={styles.footerTxt}>---- 没有更多数据了 ---- </Text>;
  };
  return (
    <View style={styles.page}>
      <TopBar />
      <WaterfallFlow
        data={articleList}
        // 列数
        numColumns={2}
        // 列间距
        columnGap={8}
        // 行间距
        rowGap={4}
        // 触顶下拉刷新
        onRefresh={refreshNewData}
        // 触底加载更多数据
        onLoadMore={loadMoreData}
        // 是否在刷新
        refreshing={store.refreshing}
        // 列表顶部
        renderHeader={() =>
          (!isLoading_type && (
            <TypeBar
              allCategoryList={store.categoryList}
              onCategoryChange={(category: Category) => {
                console.log(JSON.stringify(category));
              }}
            />
          )) || <></>
        }
        // 列表项
        renderItem={renderItem}
        // 列表底部
        renderFooter={Footer}
      />
    </View>
  );
});
const styles = StyleSheet.create({
  page: {
    paddingBottom: 50,
  },
  item: {
    width: (SCREEN_WIDTH - 18) >> 1,
    backgroundColor: "white",
    marginLeft: 6,
    marginBottom: 6,
    borderRadius: 8,
    overflow: "hidden",
  },
  countTxt: {
    fontSize: 14,
    color: "#999",
    marginLeft: 4,
  },
  titleTxt: {
    fontSize: 14,
    color: "#333",
    marginHorizontal: 10,
    marginVertical: 4,
  },
  nameLayout: {
    width: "100%",
    flexDirection: "row",
    alignItems: "center",
    paddingHorizontal: 10,
    marginBottom: 10,
  },
  avatarImg: {
    width: 20,
    height: 20,
    resizeMode: "cover",
    borderRadius: 10,
  },
  nameTxt: {
    fontSize: 12,
    color: "#999",
    marginLeft: 6,
    flex: 1,
  },
  footerTxt: {
    width: "100%",
    fontSize: 14,
    color: "#999",
    marginVertical: 16,
    textAlign: "center",
    textAlignVertical: "center",
  },
});
